<script>
  import { Notyf } from 'notyf';
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';

  let username = "";
  let password = "";
  let userType = "admin"; // 默认选择管理员
  let userData = {}; // 存储用户数据
  let notyf;

  onMount(() => {
    notyf = new Notyf({
      duration: 3000,
      className: 'x-notification',
      position: { x: 'right', y: 'top' }
    });

    refreshBackgroundImage();

  });

  function refreshBackgroundImage() {
        const body = document.querySelector('body');
        const timestamp = new Date().getTime();
        body.style.backgroundImage = `url('/ocean.png?timestamp=${timestamp}')`;
    }

  // 处理登录逻辑
  async function handleLogin() {
    const query = new URLSearchParams({
      username: username,
      userType: userType,
      password: password
    }).toString();

    fetch(`/api/login?${query}`, {
      method: 'GET'
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('登录失败');
        }
        return response.json();
      })
      .then((data) => {
        userData = data;
        console.log('登录成功');
        console.log(userData);
        notyf.success('登录成功');
        
        // 根据role跳转到不同的页面
        let targetPage = '';
        switch (userData.userType) {
          case 'admin':
            targetPage = 'admin';
            break;
          case 'comuser':
            targetPage = 'comuser';
            break;
          case 'business':
            targetPage = 'business';
            break;
          default:
            console.error('未知的用户类型');
            return;
        }

        // 1.5秒后跳转到相应的页面并传递用户数据
        localStorage.setItem('userData', JSON.stringify(userData));
        setTimeout(() => {
          goto(`/${targetPage}`, { replaceState: false, state: {userData}});
        }, 1500);
      })
      .catch((error) => {
        notyf.error(error.message || '登录请求出错');
        console.error('登录请求出错:', error);
      });
  }

  // 处理注册逻辑
  function handleRegister() {
    // 跳转至注册页面
    goto('/register');
  }
</script>

<style>
  @import 'notyf/notyf.min.css';
  
  :global(body) {
    margin: 0;
    font-family: Arial, sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-image: url('/ocean.png'); /* 使用本地背景图片 */
    background-size: cover; /* 使背景图像覆盖整个页面 */
    background-position: center; /* 使背景图像居中 */
    background-repeat: no-repeat; /* 防止背景图像重复 */
  }

  #container {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  #login_box {
    width: 600px; /* 增加宽度 */
    height: auto;
    background-color: rgba(255, 255, 255, 0.4); /* 设置背景为白色，添加透明度 */
    text-align: center;
    border-radius: 15px; /* 增加圆角 */
    padding: 60px; /* 增加内边距 */
    color: black;
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.5); /* 增加阴影 */
  }

  h2 {
    color: #333;
    margin-top: 5%;
    font-size: 2.5em; /* 增加字体大小 */
    background: linear-gradient(90deg, #330867, #30cfd0); /* 蓝紫渐变颜色 */
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加阴影 */
    font-weight: bold; /* 增加字体粗细 */
  }

  .input_box {
    margin-top: 5%;
  }

  input, select {
    border: 1px solid #ccc;
    width: 80%;
    font-size: 18px; /* 增加字体大小 */
    color: #333;
    background: #f9f9f9;
    padding: 12px; /* 增加内边距 */
    outline: none;
    margin-top: 10px;
    border-radius: 5px;
    box-shadow: inset 0 2px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }

  input:focus, select:focus {
    border-color: #30cfd0;
    box-shadow: 0 0 5px rgba(48, 207, 208, 0.5);
    background: #fff;
  }

  button {
    margin-top: 20px;
    width: 80%;
    height: 45px; /* 增加高度 */
    border-radius: 10px;
    border: 0;
    color: #fff;
    text-align: center;
    line-height: 45px; /* 调整行高 */
    font-size: 16px; /* 增加字体大小 */
    background-image: linear-gradient(to right, #30cfd0, #330867);
    cursor: pointer;
    transition: background-image 0.3s ease;
  }

  button:hover {
    background-image: linear-gradient(to right, #330867, #30cfd0);
  }
</style>

<div id="container">
  <div id="login_box">
    <h2>王岳伟&田晨旭的在线购物系统</h2>
    <div class="input_box">
      <select bind:value={userType}>
        <option value="admin">选择登入角色:管理员</option>
        <option value="comuser">选择登入角色:普通用户</option>
        <option value="business">选择登入角色:商户</option>
      </select>
    </div>
    <div class="input_box">
      <input type="text" bind:value={username} placeholder="请输入账号" />
    </div>
    <div class="input_box">
      <input type="password" bind:value={password} placeholder="请输入密码" />
    </div>
    <button on:click={handleLogin}>登录</button>
    <button on:click={handleRegister}>注册</button>
  </div>
</div>